package com.fyyg.common.wechat;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author hang.ouyang
 * @date 2016-04-09 17:36
 */
public class WeChatUtil {

    private final static Logger logger = LogManager.getLogger(WeChatUtil.class);


    /**
     * 格式化查询参数
     * 对参数按照key=value的格式，并按照参数名ASCII字典序排序：
     * eg：appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA
     * @param params
     * @return
     */
    public static String formatParam(Map<String,String> params){
        Iterator<String> iterator =  params.keySet().iterator();
        List<String> paramList = new ArrayList<>();
        while (iterator.hasNext()){
            String key = iterator.next();
            String value = params.get(key);
            if(null == value  || "".equals(value)){
                continue;
            }
            paramList.add(key+"="+value);
        }
        Collections.sort(paramList);
        StringBuffer sb = new StringBuffer("");
        for (String s : paramList) {
            sb.append(s);
            sb.append("&");
        }
        return sb.toString().substring(0,sb.toString().length()-1);
    }

    /**
     * 签名加密
     * @param params
     * @return
     */
    public static String sign(Map<String,String> params){
        try {
            String formatStr = formatParam(params);
            logger.info("生成字符串\t"+formatStr);
            //拼接API密钥 并对signTemp进行MD5运算，再将得到的字符串所有字符转换为大写
            String signTemp = String.format("%s&key=%s",formatStr,WeChatObject.MCH_KEY);
            logger.info("连接商户key\t"+signTemp);
            MessageDigest messageDigest =MessageDigest.getInstance("MD5");
            byte[] byteArray = signTemp.getBytes("UTF-8");
            byte[] md5Bytes = messageDigest.digest(byteArray);
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            String sign = hexValue.toString().toUpperCase();
            logger.info("md5编码并转成大写：\t"+sign);
            return sign;
        } catch (NoSuchAlgorithmException|UnsupportedEncodingException e) {
           logger.error(e.getMessage());
        }
        return null;
    }


}
